# pip install pynput
# -*- coding: utf-8 -*-
import threading
from pynput.keyboard import Key, Listener
import cv2


def on_press(key):
    global press_key
    try:
        print(key.char)
        press_key = key.char

    except AttributeError:
        print("正在按压:{}".format(key))

# 监听到ESC退出程序
def on_release(key):
    if key == Key.esc:
        # 停止监听
        return False


# 开始监听
def start_listen():
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()


if __name__ == '__main__':
    press_key = None

    t1 = threading.Thread(target=start_listen, args=())
    t1.start()
    # t1.join() #不加join的话，主线程和子线程完全是并行的, 加了join主线程得等这个子线程执行完毕，才能继续往下走

    while 1:
        img = cv2.imread('../choose.png')
        font = cv2.FONT_HERSHEY_SIMPLEX  # 定义字体
        imgzi = cv2.putText(img, press_key, (50, 50), font, 1.2, (255, 255, 255), 2)
        # 图像，文字内容， 坐标 ，字体，大小，颜色，字体厚度
        print(press_key)
        cv2.imshow("image", imgzi)
        k = cv2.waitKey(100)
        if k == 27:
            break

# 按字符会在显示在图片上, 按Esc以后退出程序

